import { _decorator, Component, director, Node } from 'cc';
import { GomokuGameEvent, GomokuGameMgr } from '../scripts/GomokuGameMgr';
import { GomokuBoardMgr } from '../../module_basic/shared/GomokuBoardMgr';
import { tgxSceneUtil, tgxUIAlert, tgxUIMgr } from '../../core_tgx/tgx';
const { ccclass, property } = _decorator;

@ccclass('GomokuAI')
export class GomokuAI extends Component {
    start() {
        let aiThinkingTime = 1.0;
        director.getScene().on(GomokuGameEvent.TURN_PLAYER_CHANGED, () => {
            this.scheduleOnce(this.onAIPlay.bind(this), aiThinkingTime);
        });

        director.getScene().on(GomokuGameEvent.PLACE_PIECE, this.onCheckResult, this);
    }

    onAIPlay() {
        if (GomokuGameMgr.inst.gameData.currentPlayer == 'ai') {
            let aigrid = GomokuGameMgr.inst.boardMgr.getBestPlaceGrid(2);
            let playerGrid = GomokuGameMgr.inst.boardMgr.getBestPlaceGrid(1);
            let info = aigrid;
            if (playerGrid.score >= aigrid.score) {
                //防守
                info = playerGrid;
            }

            GomokuGameMgr.inst.boardMgr.setGrid(info.gridX, info.gridY, 2);

            let msg = {
                uid: GomokuGameMgr.inst.gameData.currentPlayer,
                gridX: info.gridX,
                gridY: info.gridY,
                value: 2
            };
            director.getScene().emit(GomokuGameEvent.PLACE_PIECE, msg);
            GomokuGameMgr.inst.changeTurnPlayer();
        }
    }

    onCheckResult(data: { gridX: number, gridY: number }) {
        let v = GomokuGameMgr.inst.boardMgr.getGridData(data.gridX, data.gridY);
        let isWin = GomokuGameMgr.inst.boardMgr.checkWin(data.gridX, data.gridY, v);
        if (isWin) {
            let fnAlertClick = (bOK)=>{
                if(bOK){
                    GomokuGameMgr.inst.initAIMode();
                    tgxSceneUtil.reloadScene();
                }
                else{
                    GomokuGameMgr.inst.backToLobby();
                }
            };
            if (v == 1) {
                tgxUIAlert.show('你赢了! 再来一局？',true).onClick(fnAlertClick);
            }
            else {
                tgxUIAlert.show('你输了! 再来一局？',true).onClick(fnAlertClick);
            }
        }
    }

    update(deltaTime: number) {

    }
}


